package com.zhku.shoppingspringboot.common;

import org.springframework.core.convert.ConversionService;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.util.StringUtils;

/**
 * 作者：zjy
 * 时间：2024/8/24 17:13
 * 描述:无bug
 */
//自定义RedisCache，重写evict方法实现CacheEvict模糊匹配删除
public class RedisCacheResolver extends RedisCache {

    private final String name;
    private final RedisCacheWriter cacheWriter;
    private final ConversionService conversionService;

    public RedisCacheResolver(String name, RedisCacheWriter cacheWriter,
                              RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
        this.name = name;
        this.cacheWriter = cacheWriter;
        this.conversionService = cacheConfig.getConversionService();

    }

    @Override
    public void evict(Object key) {

        if (key instanceof String) {
            String keyString = key.toString();
            // 通过用通配符进行模糊匹配
            if (StringUtils.endsWithIgnoreCase(keyString, "*")) {
                evictLikeSuffix(keyString);
                return;
            }

            super.evict(key);
        }
    }

    private void evictLikeSuffix(String keyString) {
        // 后缀删除
        byte[] pattern = this.conversionService.convert(this.createCacheKey(keyString), byte[].class);
        if (pattern == null) {
            return;
        }
        this.cacheWriter.clean(this.name, pattern);
    }
}
